package sales.gz.com.salescounter.ui;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.zxing.WriterException;

import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.lang.ref.WeakReference;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import sales.gz.com.salescounter.R;
import sales.gz.com.salescounter.utils.AppContext;
import sales.gz.com.salescounter.utils.CodeCreator;
import sales.gz.com.salescounter.utils.NetworkUtil;
import sales.gz.com.salescounter.utils.ServiceFile;

public class CommitpayActivity extends Activity {

    @Bind(R.id.tx_title)
    TextView title;
    @Bind(R.id.ly_left)
    LinearLayout lyleft;
    @Bind(R.id.img_code)
    ImageView img_code;
    @Bind(R.id.produc_name)
    TextView producName;
    @Bind(R.id.money)
    TextView money;
    private static String sn = "";//订单号
    private static Context context;
    @Bind(R.id.timeout)
    TextView timeout;
    private ServiceFile serviceFile;
    private int time = 120;
    private MyHandler mHandler;
    private Handler handler = new Handler();
    private AlertDialog dialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_commitpay);
        ButterKnife.bind(this);
        initview();
    }

    private void initview() {
        context = getApplicationContext();
        serviceFile = new ServiceFile();
        title.setText("确认支付");
        money.setText(getIntent().getStringExtra("money"));
        sn = getIntent().getStringExtra("sn");
        producName.setText(getIntent().getStringExtra("product_name"));
        mHandler = new MyHandler(this);
        timeout.setText(time+"");
        mHandler.postDelayed(leftTime, 1000);
        cib_wx_pay();
    }

    @OnClick({R.id.ly_left})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.ly_left:
                finish();
                break;
        }
    }

    @Override
    protected void onDestroy() {
        // TODO Auto-generated method stub
        super.onDestroy();
        mHandler.removeCallbacks(leftTime);
        mHandler.release();
    }
    /**
     * 微信扫码支付
     */
    public void cib_wx_pay() {
        if (NetworkUtil.isNetworkConnected(CommitpayActivity.this)){
            String url = AppContext.baseurl + "api/v2/cib_wxpay";
            RequestParams params = new RequestParams(url);
            params.addBodyParameter("sn", getIntent().getStringExtra("sn"));//设备编号GetImei.getphoneimei(MainActivity.this)
            params.addBodyParameter("money", getIntent().getStringExtra("money"));//金额
            Log.i("aaa", params + "");
            x.http().post(params, new Callback.CommonCallback<String>() {
                @Override
                public void onCancelled(CancelledException arg0) {
                }

                @Override
                public void onError(Throwable arg0, boolean arg1) {
                    Toast.makeText(CommitpayActivity.this, arg0.getMessage(), Toast.LENGTH_SHORT).show();
                }

                @Override
                public void onFinished() {
                }

                @Override
                public void onSuccess(String result) {
                    try {
                        JSONObject jsonObject = new JSONObject(result);
                        if ("0".equals(jsonObject.getString("ref"))) {
                            Bitmap bitmap;
                            try {
                                bitmap = CodeCreator.createQRCode(jsonObject.getJSONObject("result").getString("wx_qrcode"));
                                img_code.setImageBitmap(bitmap);
                                Log.i("aaa","开始");
                                new Handler().postDelayed(new Runnable() {
                                    @Override
                                    public void run() {
                                        get_pay_result();
                                    }
                                },5000);
                            } catch (WriterException e) {
                                e.printStackTrace();
                            }
                        } else {
                            Toast.makeText(CommitpayActivity.this, jsonObject.getString("msg"), Toast.LENGTH_SHORT).show();
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            });

        }else{
            Toast.makeText(CommitpayActivity.this,"抱歉,网络异常",Toast.LENGTH_LONG).show();
        }


    }
    /**
     * 查询订单的支付结果
     */
    public void get_pay_result() {
        if(NetworkUtil.isNetworkConnected(CommitpayActivity.this)){
            String url = AppContext.baseurl + "api/v2/get_pay_result";
            RequestParams params = new RequestParams(url);
            params.addBodyParameter("sn", sn);
            params.setConnectTimeout(3000);
            Log.i("aaa", params + "");
            x.http().get(params, new Callback.CommonCallback<String>() {
                @Override
                public void onCancelled(CancelledException arg0) {
                }

                @Override
                public void onError(Throwable arg0, boolean arg1) {
                    get_pay_result();
                }

                @Override
                public void onFinished() {
                }

                @Override
                public void onSuccess(String result) {
                    try {
                        JSONObject jsonObject = new JSONObject(result);
                        if ("0".equals(jsonObject.getString("ref"))) {
                            Intent intent = new Intent(CommitpayActivity.this,PayStatusActivity.class);
                            intent.putExtra("box_no",jsonObject.getString("result"));
                            startActivity(intent);
                        } else {
                            if (Integer.parseInt(timeout.getText().toString())>0){//说明时间还不到120秒
                                new Handler().postDelayed(new Runnable() {
                                    @Override
                                    public void run() {
                                        get_pay_result();
                                    }
                                },3000);
                            }else{
                                Toast.makeText(CommitpayActivity.this,"您未支付成功",Toast.LENGTH_LONG).show();
                                System.exit(0);
                            }
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            });

        }else{
            Toast.makeText(CommitpayActivity.this,"抱歉,网络异常",Toast.LENGTH_LONG).show();
        }


    }

    /**
     * 支付时间限制
     */
    private Runnable leftTime = new Runnable() {

        @Override
        public void run() {
            if(time>0){

                timeout.setText(time+"");
                mHandler.postDelayed(leftTime, 1000);
                time--;
            }else{
                System.exit(0);//杀死进程释放资源
            }

        }
    };
    private static class MyHandler extends Handler {
        private CommitpayActivity mOuter;

        public MyHandler(CommitpayActivity outer) {
            this.mOuter = outer;
        }

        public void release() {
            new WeakReference<CommitpayActivity>(mOuter);
        }

        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 0:
                    break;

                default:
                    break;
            }
        }
    }

}
